package com.pacifictextiles.qc.inspection.server.controller.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.pacifictextiles.qc.inspection.server.model.dao.impl.BatchDAOImpl;
import com.pacifictextiles.qc.inspection.server.model.dao.impl.DefectDAOImpl;
import com.pacifictextiles.qc.inspection.server.model.dao.impl.RollDAOImpl;
import com.pacifictextiles.qc.inspection.server.model.dao.impl.WasteDAOImpl;
import com.pacifictextiles.qc.inspection.server.model.vo.Batch;
import com.pacifictextiles.qc.inspection.server.model.vo.Defect;
import com.pacifictextiles.qc.inspection.server.model.vo.Roll;
import com.pacifictextiles.qc.inspection.server.model.vo.Waste;

public class SendBatchSVL extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	// 接收BatchNO
	// 执行数据库查询
	// 生成Batch对象，RollList，DefectList，WasteList
	
    public SendBatchSVL() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");

		// 获取请求参数
		String fullCode = request.getParameter("fullCode");

		// 数据库操作对象
		BatchDAOImpl bdi = new BatchDAOImpl();
		RollDAOImpl rdi = new RollDAOImpl();
		DefectDAOImpl ddi = new DefectDAOImpl();
		WasteDAOImpl wdi = new WasteDAOImpl();
		
		// 数据存储对象
		Batch batch = new Batch();
		
		// JSON打包对象
		JSONPackager jp = new JSONPackager();
		
		PrintWriter out = response.getWriter();
		
		// 执行数据库操作
		try {
			batch = bdi.getBatch(fullCode);
			
			if (batch != null) {
				
				// 获取该缸布的布匹信息
				List<Roll> rollList = rdi.getRollList(fullCode);
				
				// 获取每一匹布的defect、waste list
				for (Roll roll : rollList) {
					List<Defect> defectList = ddi.getDefectList(roll.getRollNo());
					List<Waste> wasteList = wdi.getWasteList(roll.getRollNo());
					roll.setDefectList(defectList);
					roll.setWasteList(wasteList);
				}
				
				// 讲rolls信息加入batch
				batch.setRollList(rollList);
				
				// 打包成JSON对象
				JSONObject batchJSONObject = jp.packageBatch(batch);
				out.write(batchJSONObject.toString());
				out.flush();
			}
		} catch (Exception e) {
			// e.printStackTrace();
			System.out.print("Send Batch Servlet:  打包batch对象失败" + "\n\n");
		}
		out.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}
}
